# -*- coding: utf-8 -*-
"""
    :author: zjwei (卫占军)
    :copyright: © Wei Zhanjun <weizj2000@gmail.com@gmail.com>
    :date: 2020/10/29
"""
import requests
from flask import request, abort, jsonify
from flask_restful import Resource, reqparse


class LarkNotication(Resource):
    def post(self):
        if not request.json:
            abort(404)
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, help='please input username', required=True, location='json')
        parser.add_argument('email', type=str, help='please input email', required=True, location='json')
        parser.add_argument('tel', type=str, location='json')
        parser.add_argument('company', type=str, help='please input company', required=True, location='json')
        parser.add_argument('region', type=str, help='please input region', required=True, location='json')
        parser.add_argument('country', type=str, help='please input country', required=True, location='json')
        parser.add_argument('purpose', type=str, help='please input purpose', required=True, location='json')
        parser.add_argument('message', type=str, help='please input message', required=True, location='json')
        args = parser.parse_args()
        args = dict(args)

        name = args.get("name")
        email = args.get("email")
        tel = args.get("tel", "")
        company = args.get("company")
        purpose_map = {
            "1": ["option1", "Business Collaboration"],
            "2": ["h0583Agq1", "Personal Purchase"],
            "3": ["yLw28jrW3", "Developer"],
            "4": ["7k3Dtu0t6", "Customer Support"]
        }
        purpose = purpose_map[args.get("purpose")][0]
        message = args.get("message")
        region_map = {
            "1": ["SGrqo578a", "f722b96fe8304d4fa58b7c4f888a59c4", "Asia Pacific"],
            "2": ["DzI741Gdh", "e1fb7dc28e5943efb3628a27cf1fec3b", "Europe"],
            "3": ["RDTEj806n", "e1fb7dc28e5943efb3628a27cf1fec3b", "North America"],
            "4": ["", "e1fb7dc28e5943efb3628a27cf1fec3b", "Others"]
        }
        region = region_map[args.get("region")][0]
        leads_pool = region_map[args.get("region")][1]
        country = args.get("country")
        result = create_record(name=name, email=email, tel=tel, company=company, region=region, leads_pool=leads_pool,
                               country=country, purpose=purpose, message=message)
        code = result.get("errorCode")
        return jsonify({"code": code, "msg": result.get("errorMessage", "ok")})


def get_access_token():
    url = "https://open.fxiaoke.com/cgi/corpAccessToken/get/V2"
    appid = "FSAID_1318e02"
    appsecret = "9b021b468b3048feb9c2342ee2386d11"
    permanentcode = "F785A27776526B83B30229E81D28E931"
    req_data = {
        "appId": appid,
        "appSecret": appsecret,
        "permanentCode": permanentcode
    }
    res = requests.post(url, json=req_data)
    return res.json().get("corpAccessToken", None)


def create_record(name, email, tel, company, region, leads_pool, country, purpose, message):
    url = "https://open.fxiaoke.com/cgi/crm/v2/data/create"
    req_data = {
        "corpAccessToken": get_access_token(),
        "corpId": "FSCID_2BB0AF683B017C864FF2FE4FFB38B301",
        "currentOpenUserId": "FSUID_71E457D67671B4FA5FA7A63C0F7E9C68",
        "data": {
            "object_data": {
                "dataObjectApiName": "LeadsObj",
                "name": name,
                "email": email,
                "mobile": tel,
                "company": company,
                "field_8Lh2M__c": region,
                "leads_pool_id": leads_pool,
                "field_wAGyB__c": country,
                "field_YHxM1__c": purpose,
                "remark": message,
                "source": "6"
            }
        }
    }
    res = requests.post(url, json=req_data)
    return res.json()

def lark_message_card(robot_url, title, text, img_list, url, user_url):
    post_url = robot_url
    # 文本主体
    elements = [{
        "tag": "div",
        "text": {
            "content": text,
            "tag": "lark_md"
        }
    }]
    # 图片列表添加
    for img in img_list:
        if img:
            elements.append({"tag": "hr"})
            elements.append({
                "tag": "img",
                "img_key": img,
                "alt": {
                    "tag": "plain_text",
                    "content": "Twitter-img"
                }
            })
    # 添加跳转按钮
    elements.append({
                    "actions": [
                        {
                            "tag": "button",
                            "text": {
                                "content": "Go to view",
                                "tag": "lark_md"
                            },
                            "url": url,
                            "type": "default",
                            "value": {}
                        }
                    ],
                    "tag": "action"
                })

    data = {"msg_type": "interactive", "card": {}}
    data["card"]["config"] = {
                "wide_screen_mode": True,
                "enable_forward": True,
            }
    data["card"]["elements"] = elements
    data["card"]["header"] = {
                "title": {
                    "content": title,
                    "tag": "plain_text"
                }
            }

    res = requests.post(post_url, json=data)
    return res.json()


def lark_upload_image(url):
    post_url = "https://nbms.nreal.ai/api/v1/feishu/upload_img"
    res = requests.post(post_url, data={"url": url})
    return res.text
